package com.ruoyi.web.controller.api;

import java.util.Date;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.system.domain.SysTestRecord;
import com.ruoyi.system.mapper.SysTestRecordMapper;
import com.ruoyi.system.service.ISysStudentCourseService;
import com.ruoyi.system.service.ITestRecordService;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;

/**
 * 测试记录接口
 * 
 * @author ruoyi
 */
@Api(tags = "测试记录接口")
@RestController
@RequestMapping("/api/v1/test")
public class TestRecordController extends BaseController {
	
    @Autowired
    private SysTestRecordMapper sysTestRecordMapper;
    
    @Autowired
    private ITestRecordService testRecordService;
    @Autowired
    private ISysStudentCourseService sysStudentCourseService;

    /**
     * 获取学员记录列表
     * @throws Exception 
     */
    @PostMapping("/list")
    public TableDataInfo list(@RequestBody String body) throws Exception
    {
    	JSONObject bodyJO = JSON.parseObject(body);
    	SysTestRecord entity = JSON.parseObject(body, SysTestRecord.class);
    	Date beginTime = bodyJO.getDate("beginTime");
    	Date endTime = bodyJO.getDate("endTime");
    	Integer pageNo = bodyJO.getInteger("pageNo");
    	String unitName = bodyJO.getString("unitName");
    	String studentName = bodyJO.getString("studentName");
    	if (pageNo == null) {
    		throw new Exception("页码不能为空");
		}
    	
    	Integer pageSize = bodyJO.getInteger("pageSize");
    	
        entity.setStudentId(SecurityUtils.getLoginStudentId());
        List<SysTestRecord> list = testRecordService.list(entity, beginTime, endTime, pageNo, pageSize, unitName, studentName);
        Integer total = sysTestRecordMapper.count(entity, beginTime, endTime, unitName, studentName);
        return getDataTable(list, total.longValue());
    }
    
    /**
     * 提交测试记录
     */
    @ApiOperation("提交测试记录")
    @PostMapping("/submit")
    public AjaxResult submit(@RequestBody SysTestRecord entity) {
        // 保存测试记录
    	entity.setStudentId(SecurityUtils.getLoginStudentId());
        testRecordService.insertTestRecord(entity);
        
        // 完成课程
        Long studentId = entity.getStudentId();
        Long courseId = entity.getCourseId();
        sysStudentCourseService.finishStudentCourse(studentId, courseId);
        
        return AjaxResult.success();
    }
}